package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.query.PageList;
import cn.itsource.basic.service.IBaseService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * 公共的接口实现类
 */
@Transactional
public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T,Q> {

    /**
     * 注入公共的持久层依赖
     * @return
     */
    @Autowired
    private Mapper<T> mapper;


    @Override
    public List<T> getAll() {
        return mapper.selectAll();
    }

    @Override
    public PageList<T> getAllByPage(Q o) {
        // 1. 设置分页参数
        PageHelper.startPage(o.getPageNum(), o.getPageSize());
        // 2. 执行查询操作
        List<T> t = mapper.selectAll();
        // 3. 封装分页数据
        PageInfo<T> pageInfo = new PageInfo<>(t);
        // 4. 使用自己的工具类返回分页数据
        PageList<T> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());
        // 5. 返回数据
        return pageList;
    }

    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(T t) {
        // 如果id有值就是修改，否则就是新增
        if (t.getId() == null) {
            mapper.insertSelective(t);
        } else {
            mapper.updateByPrimaryKeySelective(t);
        }
    }
}
